import React, { useState, useRef, useEffect } from 'react';
import { Send } from 'lucide-react';
import { useAIChat } from '@/contexts/aiChat';

/**
 * 消息输入组件
 * 用于输入和发送消息
 */
const MessageInput: React.FC = () => {
  const [message, setMessage] = useState('');
  const { sendMessage } = useAIChat();
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // 自动调整文本框高度
  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
      textareaRef.current.style.height = `${Math.min(
        textareaRef.current.scrollHeight,
        120 // 最大高度
      )}px`;
    }
  }, [message]);

  // 处理发送消息
  const handleSendMessage = () => {
    if (message.trim()) {
      sendMessage(message);
      setMessage('');
      
      // 重置文本框高度
      if (textareaRef.current) {
        textareaRef.current.style.height = 'auto';
      }
    }
  };

  // 处理按键事件
  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    // 回车发送，Shift+回车换行
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  return (
    <div className="border-t p-3 flex-shrink-0">
      <div className="flex items-end space-x-2">
        <div className="flex-1 relative">
          <textarea
            ref={textareaRef}
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="输入消息..."
            className="w-full resize-none border rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary min-h-[40px] max-h-[120px]"
            rows={1}
          />
        </div>
        <button
          onClick={handleSendMessage}
          disabled={!message.trim()}
          className="bg-gray-800 hover:bg-gray-700 text-white rounded-full w-10 h-10 flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex-shrink-0"
          aria-label="发送消息"
        >
          <Send className="w-5 h-5" />
        </button>
      </div>
    </div>
  );
};

export default MessageInput;
